<template>
    <div>
        <input type="text" v-model="keyword">
        <input type="button" value="搜索" @click="btnQuery">
        <input type="button" value="添加" @click="btnAdd">
    </div>
    <div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in bookList" :key="item.id">
                    <td>{{ item.id }}</td>
                    <td>{{ item.bookName }}</td>
                    <td>{{ item.author }}</td>
                    <td>
                        <input type="button" value="编辑" @click="btnEdit(item.id)">
                        <input type="button" value="删除" @click="btnDel(item.id)">
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup>
import { onMounted, ref } from "vue"
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = new useRouter()

const url = 'http://localhost:8000'

const keyword = ref('')
const bookList = ref([])

onMounted(async () => {
    const data = await axios.get(`${url}/book`)
    bookList.value = data.data.data
})

async function btnQuery() {
    if (keyword.value) {
        const data = await axios.get(`${url}/book?keyword=${keyword.value}`)
        bookList.value = data.data.data
    } else {
        const data = await axios.get(`${url}/book`)
        bookList.value = data.data.data
    }
}

function btnAdd() {
    router.push('/bookAdd')
}

function btnEdit(id) {
    router.push(`/bookEdit/${id}`)
}

async function btnDel(id) {
    if (confirm('确定要删除吗？')) {
        const data = await axios.delete(`${url}/book/${id}`)
        if (data.data.code === 200) {
            alert('删除成功')
            const data = await axios.get(`${url}/book`)
            bookList.value = data.data.data
        }
    }
}

</script>